<?php


namespace app\admin\services\hwObs;


use Obs\ObsClient;

class HWYObs
{
    protected $obsClient;
    protected $key = '6CBBTZYACGMS355OBVWN';
    protected $secret = 'nY612Ca9bKorVnrdAhqLjnpOIvVAqHCe5fD5XReM';
    protected $endpoint = 'https://obs.cn-south-1.myhuaweicloud.com';
    protected $bucketname = 'jjjsp';

    protected $obs_url = 'https://jjjsp.obs.cn-south-1.myhuaweicloud.com';

    public function __construct(array $conf = null)
    {
        $key = $conf['key'] ?? $this->key;
        $secret = $conf['secret'] ?? $this->secret;
        $endpoint = $conf['endpoint'] ?? $this->endpoint;

        $this->init($key, $secret, $endpoint);
    }


    /**
     * 创建ObsClient实例
     * @param $key Provide your Access Key
     * @param $secret  Provide your Secret Key
     * @param $endpoint https://your-endpoint
     */
    public function init($key, $secret, $endpoint)
    {
        $this->obsClient = new ObsClient([
            'key' => $key,
            'secret' => $secret,
            'endpoint' => $endpoint
        ]);
    }

    /**
     * 上传
     * @param $path
     * @param null $key
     * @return string
     */
    public function uploadObs($path, $key = null)
    {
        $resp = $this->obsClient->putObject([
            'Bucket' => $this->bucketname,
            'Key' => $key,
            'SourceFile' => $path
        ]);
        if ($resp['HttpStatusCode'] != 200) {
            throw new Exception('上传失败，请稍后重试');
        }
        return $this->obs_url . '/' . $key;
    }

    /**
     * 删除
     * @param $key
     * @return string
     */
    public function deleteObs($key)
    {
        $resp = $this->obsClient->deleteObject([
            'Bucket' => $this->bucketname,
            'Key' => $key,
        ]);
        return $resp;
    }
}